<?php
/**
 * [去除html除某个标签外的所有标签]
 * @author [liyun]
 * @param  [string] $str [需要去除的字符串]
 * @param  [string] $tag ["img"或"img|a|p"标签]
 * @return [mix]    [false|str]
 */
echo "123";die();
function replace_tag_except($str, $tag=''){
	if(empty($str)){
		return false;
	}

	if ("" == $tag) {
		return strip_tags($str,"");
	} else {
		$patternTag = "/<(?!(|\/)($tag)).*?>/i";
		return preg_replace($patternTag, "", $str);
	}
}

/**
 * [去除html某个标签]
 * @author [liyun]
 * @param  [string] $str [需要去除的字符串]
 * @param  [string] $tag ["img"或"img|a|p" 标签]
 * @return [mix]      [false|str]
 */
function replace_tag($str, $tag=""){
	if(empty($str)){
		return false;
	}
	if ("" == $tag) {
		return strip_tags($str,"");
	} else {
		$patternTag = "/<(|\/)($tag).*?>/i";
		return preg_replace($patternTag, "", $str);
	}
}

/**
 * [table中的内容转换成数组形式]
 * @author [liyun]
 * @param  [string] $str [需要转换的字符串]
 * @return [mix]      [false|array(二维)]
 */
function table_to_array($str,$trim = false){
	if (empty($str)) {
		return false;
	}
	  
	//判断是否存在table标签
	$patternTable = "/<table[\s\S]*?<\/table>/i";
	if (false == preg_match($patternTable, $str ,$table)) {
		   throw new BaseException("can not find table tag");
	}
	// print_r($table);die();
	//提取行tr
	$patternTr = "/<tr[\s\S]*?<\/tr>/i";
	preg_match_all($patternTr, $table[0], $arrTr);

	//提取行th
	$patternTh = "/<th[\s\S]*?<\/th>/i";
	preg_match_all($patternTh, $table[0], $arrTh);
	$table = array();
	foreach ($arrTh[0] as $key => $th){
	    if($trim)
		  $arrTh[0][$key] = preg_replace("/&nbsp;|\s/", "", strip_tags($th,""));
	    else 
	        $arrTh[0][$key] = trim(strip_tags($th,""));
	}
	if (!empty($arrTh[0])) {
		array_push($table, $arrTh[0]);
	}
	// print_r($table);die();

	//提取每行每列td
	$patternTd = "/<td[\s\S]*?<\/td>/i";
	foreach ($arrTr[0] as $tr) {
		preg_match_all($patternTd, $tr, $arrTd);
		foreach ($arrTd[0] as $key => $td){
		    if($trim)
		        $arrTd[0][$key] = preg_replace("/&nbsp;|\s/", "", strip_tags($td,""));
		    else 
		        $arrTd[0][$key] = trim(strip_tags($td,""));
		}
		if (!empty($arrTd[0])) {
			array_push($table, $arrTd[0]);
		}
	}
	return $table;
}

